/* C standard library */
#include <errno.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>

/* POSIX */
#include <unistd.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <syscall.h>
#include <sys/ptrace.h>

#include "fork_and_exec.h"

#define FATAL(...) \
    do { \
        fprintf(stderr, "strace: " __VA_ARGS__); \
        fputc('\n', stderr); \
        exit(EXIT_FAILURE); \
    } while (0)

// 执行命令，返回PID
int do_exec_with_args(char **argv, enum wait_pid_type is_wait_pid)
{
    int argv_index = 1;
    pid_t pid = fork();
    switch (pid) {
        case -1: /* error */
            FATAL("Fork %s", strerror(errno));
        case 0:  /* child */
            //ptrace(PTRACE_TRACEME, 0, 0, 0);
            printf("Child %d exec: %s", getpid(), argv[argv_index]);
            //close(0);
            //close(1);
            //close(2);
            execvp(argv[argv_index], argv + argv_index);
            FATAL("exec %s", strerror(errno));
        default:
        /* parent */
        //printf("Child PID is %d\n", pid);
        //printf("P %d\n", getpid());
        if(is_wait_pid == WAIT_PID_TYPE_WAIT)
        {
            waitpid(pid, 0, 0);
        }
        return pid;
    }
    return 0;
}

